/**
 * Created by 叶子 on 2017/7/30.
 * http通用工具函数
 */
import * as axios from "axios";
import {message} from "antd";
import {store} from "@/index";

const baseUrl = 'http://localhost:6080/Album';

axios.defaults.baseURL = baseUrl;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


export const get = (url, params='') => {
    return request(url, params);
};

export const post = (url, params) => {
    return request(url, params, 'post');
};

export const post_body = (url, body) => {
    return request(url, undefined, 'post', body);
};

export const delete_req = (url, params) => {
    return request(url, params, 'delete');
};

export const put = (url, params) => {
    return request(url, params, 'put');
};

export const put_body = (url, body) => {
    return request(url, undefined, 'put', body);
};

/*
 get : params 是object对象
 post : FormData对象
 */
const request = (url, params, method = 'get', data) => {
    message.destroy();
    let isOk = false;
    let http;
    let headers = {};

    if (method === 'put') {
        if (params) {
            headers = {'Content-Type': 'application/x-www-form-urlencoded'};
        }
        if (data) {
            headers = {'Content-Type': 'application/json'};
        }
    }
    if (method === 'post') {
        if (params) {
            const format = new FormData();
            for (let temp in params) {
                let val = params[temp];
                if (params.hasOwnProperty(temp)) {
                    if (val instanceof Array) {
                        val.forEach((item) => {
                            format.append(temp, item);
                        })
                    } else {
                        format.append(temp, val);
                    }
                }
            }
            headers = {'Content-Type': 'form-data'};
            params = null;
            data = format;
        }
    }

    http = axios.request({
        url,
        method,
        params,
        data,
        headers
    });
    return new Promise((resolve, reject) => {
        http.then(function (response) {
            if (response.status === 401) {
                message.warn("没有权限");
            }
            if (response.status === 200) {
                isOk = true;
            }
            return response.data;
        }).then(data => {
            if (isOk && data.status === 0) {
                if (method !== 'get') {
                    message.success(data.message);
                }
                resolve(data.data);
            } else {
                message.warn(data.message);
                reject(data);
            }
        })
            .catch(function (error) {
                reject(error);
            });
    });
};
